/**
 * 视图工具
 *
 * @class IBizViewState
 */
class IBizViewState {

    /**
     * 视图状态实例管理对象
     *
     * @private
     * @static
     * @type {IBizViewState}
     * @memberof IBizViewState
     */
    private static iBizViewState: IBizViewState = null;

    /**
     * Creates an instance of IBizViewState.
     * 创建 IBizViewState 实例
     * 
     * @param {*} [opts={}]
     * @memberof IBizViewState
     */
    private constructor(opts: any = {}) { }

    /**
     * 获取 IBizViewState 单例
     *
     * @private
     * @static
     * @returns {IBizViewState}
     * @memberof IBizViewState
     */
    public static getInstance(): IBizViewState {
        if (!this.iBizViewState) {
            this.iBizViewState = new IBizViewState();
        }
        return this.iBizViewState;
    }

    /**
     * 加载视图状态
     *
     * @param {string} viewid
     * @param {*} [viewstate={}]
     * @returns {*}
     * @memberof IBizViewState
     */
    public loadViewStates(viewid: string): Subject<any> {
        const subject: Subject<any> = new rxjs.Subject();
        if (Object.is(IBizEnvironment.address, 'remote')) {
            subject.next(Cookies.get(viewid));
            subject.complete();
        } else {
            let data: any = { srfaction: 'load', viewid: viewid };
            IBizHttp.getInstance().post(IBizEnvironment.url, data).subscribe((success: any) => {
                let viewstate = '';
                if (success.ret === 0) {
                    viewstate = success.viewstate;
                }
                subject.next(viewstate);
                subject.complete();
            }, (error: any) => {
                subject.next('');
                subject.complete();
            });
        }
        return subject;
    }

    /**
     * 保存视图状态
     *
     * @param {string} viewid
     * @param {*} [viewstate={}]
     * @memberof IBizViewState
     */
    public saveViewStates(viewid: string, viewstate: any = {}): void {
        if (Object.is(IBizEnvironment.address, 'remote')) {
            Cookies.set(viewid, JSON.stringify(viewstate));
        } else {
            let data: any = { srfaction: 'save', viewid: viewid, viewstate: JSON.stringify(viewstate) };
            IBizHttp.getInstance().post(IBizEnvironment.url, data);
        }
    }
}